package top.lixunda.ecommerce.server.good.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import top.lixunda.commerce.common.core.entity.MessageObject;
import top.lixunda.commerce.common.core.exception.AppException;
import top.lixunda.commerce.common.core.exception.InternalApiException;
import top.lixunda.common.validate.exception.XumValidException;

/**
 * @author LiXunda
 * @version time:2019/10/29 17:54
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 该异常一般由feign内部调用错误抛出
     *
     * @param e InternalApiException
     * @return 状态码正常，MessageObject为普通错误，提示消息为exception中的msg
     */
    @ExceptionHandler(InternalApiException.class)
    public ResponseEntity<MessageObject> internalApiException(InternalApiException e) {
        // 正常情况该异常应该继续返回异常，而不是结果
        log.debug("处理异常 InternalApiException : status:{}  code:{}  msg:{}", e.getHttpStatus(), e.getMsgCode(), e.getMsg());
        return ResponseEntity.status(HttpStatus.OK).body(MessageObject.error(e.getMsg()));
    }

    @ExceptionHandler(AppException.class)
    public ResponseEntity<MessageObject> appException(AppException e) {
        log.debug("处理了AppException {}", e.getMsg());
        MessageObject messageObject = MessageObject.error(e.getMsg());
        if(e.getCode() != null){
            messageObject.setCode(e.getCode());
        }
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(messageObject);
    }

    /**
     * 参数验证错误，可能是验证过程中的bug，也可能是发现了参数错误
     *
     * @param e Exception
     * @return MessageObject
     */
    @ExceptionHandler(XumValidException.class)
    public ResponseEntity<MessageObject> validException(XumValidException e) {
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(MessageObject.error(e.getMessage()));
    }

}
